package org.example.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

public class URLEncodedUtils {

    public static String format(Map<Object, Object> parameters) {
        return format(parameters, '&', "UTF-8");
    }

    public static String format(Map<Object, Object> parameters, String charset) {
        return format(parameters, '&', charset);
    }

    public static String format(Map<Object, Object> parameters, char parameterSeparator, String charset) {
        StringBuilder result = new StringBuilder();
        parameters.forEach((k, v) -> {
            if (result.length() > 0) {
                result.append(parameterSeparator);
            }
            try {
                String encodedName = URLEncoder.encode(String.valueOf(k), charset);
                String encodedValue = URLEncoder.encode(String.valueOf(v), charset);
                result.append(encodedName).append("=").append(encodedValue);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        });
        return result.toString();
    }

}
